<?php	
    class ControlPanel
    {
        public static $connection;
        public static $user;
        public $name;
        public $error;
        public $action;
        protected $header;
        protected $footer;
        public function __construct($name)
        {
            self::$connection = new Connection();
            self::$user       = new Login();
            $this->name       = $name;
        }
        public function render()
        {
            $this->header = CP_BAS . '/header.php';
            $this->footer = CP_BAS . '/footer.php';
            $request      = CP_BAS . $this->getURI(($req = $this->getRQS()));
			$login = self::$user;
            $this->error  = "";
            $this->message  = "";
            $this->action  = "";
            $conf         = Config::getAccess();
			if (isset($req['action']))
				$this->action  = $req['action'];
            if (!isset($req['module']))
                $req['module'] = 'main';
            if ($conf->getPage($req['module']) == NOT_ACCESSIBLE)
            {
                include $this->header;
                include CP_BAS . "error/naccess.php";
                include $this->footer;
                exit;
            } //$conf->getPage($req['module']) == NOT_ACCESSIBLE
			
            if (!$login->isLoggedIn() 
				&& isset($req['action'])
				&& isset($req['module'])
				&& ($conf->getPage($req['module']) == MEMBER 
				|| $conf->getPage($req['action']) == MEMBER))
            {
                $this->redirect('index.php?module=login');
                exit;
            } //!$login->isLoggedIn() && ($conf->getPage($req['module']) == MEMBER || $conf->getPage($req['action']) == MEMBER)
			$group = 0;
			switch($login->type){
				case 99:
					$group = 1;
					break;
				case 4:
					$group = 2;
					break;
				case 5:
					$group = 4;
					break;
			}
			if ($conf->getAccess($req['action']) != NON_MEMBER && ($conf->getAccess($req['action'])&$group) == false)
            {
                include $this->header;
                include CP_BAS . "error/naccess.php";
                include $this->footer;
                exit;
            }
			
            if (file_exists($this->header))
            {
                if (file_exists($request))
                    if (file_exists(str_replace(CP_BAS, CP_MOD, $request)))
                        include str_replace(CP_BAS, CP_MOD, $request);
                if (!isset($req['ajax']))
                    include $this->header;
            } //file_exists($this->header)
			if (file_exists(($request2=CP_BAS . $this->getActionPath($req))))
			{
                if (file_exists(str_replace(CP_BAS, CP_MOD, $request2)))
                        include str_replace(CP_BAS, CP_MOD, $request2);
                include $request2;
                self::$user = $login;
			}
			else if (file_exists($request))
            {
                include $request;
                self::$user = $login;
            } //file_exists($request)
            else
            {
                $this->error = $request;
                include CP_BAS . "error/index.php";
                //$this->redirect();
            }
            if (!isset($req['ajax']) && file_exists($this->footer))
            {
                include $this->footer;
            } //!$req['ajax'] && file_exists($this->footer)
        }
        public function render2($path)
        {
            $login = self::$user;
            $conf  = Config::getAccess();
            //if ( $conf->getPage($req['module']) == NOT_ACCESIBLE ){
            //    $this->redirect('index.php?module=login');
            //    exit;
            //}
            //if ( !$login->isLoggedIn() && $conf->getPage($req['module'])  != MEMBER ){
            //    $this->redirect('index.php?module=login');
            //    exit;
            //}
            if (file_exists($path))
            {
                if (file_exists($a = str_replace(CP_BAS, CP_MOD, $path)))
                    include str_replace(CP_BAS, CP_MOD, $path);
                include $path;
                self::$user = $login;
            } //file_exists($path)
            else
            {
                $this->error = $path;
                include CP_BAS . "error/index.php";
                //$this->redirect();
            }
        }
        private function getURI($arr)
        {
            if (!isset($arr['module']))
                return "main/index.php";
            if (!isset($arr['action']))
                return sprintf("%s/index.php", $arr['module']);
            return sprintf("%s/%s.php", $arr['module'], $arr['action']);
        }
		private function getActionPath($arr)
        {
			$temp = "";
            if (!$arr['module'])
                return "main/index.php";
			while ($act = current($arr)) {
				if (strpos(key($arr), 'action') !== FALSE) {
					$temp = $temp . "/" . $act;
				}
				next($arr);
			}
			if (!isset($arr['page']))
				return sprintf("%s%s/index.php", $arr['module'], $temp);
            return sprintf("%s%s/%s.php", $arr['module'], $temp, $arr['page']);
        }
        private function getRQS()
        {
            $arr = array();
            foreach (explode('&', trim($_SERVER['QUERY_STRING'], '&')) as $line)
            {
				$kv = explode('=', $line, 2);
				if (!isset($kv[0]) || !isset($kv[1]))
					continue;
                list($key, $val) = $kv;
				$arr[$key] = $val;
            } //explode('&', trim($_SERVER['QUERY_STRING'], '&')) as $line
            return $arr;
        }
        public function path($path)
        {
            echo CP_BAS . $path;
        }
        public function redirect($location = null, $timeout = 0, $html = 0)
        {
            if (is_null($location))
            {
                $location = Config::$url;
            } //is_null($location)
            if ($html == 0)
            {
                $second = $timeout / 1000;
                if ($second > 0)
                    header("Refresh: $second;Location: $location");
                else
                    header("Location: $location");
            } //$html == 0
            else{
                echo "<span id='redirect' url='$location' timeout='$timeout' style='display:none;' ></span>";
			}
        }
        public function get($var)
        {
            if (count($_POST) && isset($_POST[$var]))
            {
                return $_POST[$var];
            } //count($_POST)
            if (count($_GET) && isset($_GET[$var]))
            {
                return $_GET[$var];
            } //count($_GET)
            return "";
        }
		public function isType($login, $type)
		{
			if ($login->type == $type)
			{
				return true;
			}
			return false;
		}
		public function isNormal($login)
		{
			if ($login->type == NORMAL)
			{
				return true;
			}
			return false;
		}
		public function getPageCrumb()
		{
			$link = $this->getActionPath($this->getRQS());
			echo "<div class='grid_12'><div class='breadcrumbs'>";
			$x = 0;
			$cont = explode('/', $link);
			$add = "";
			foreach ($cont as $line)
			{
				if ($line == 'index.php' || ($x++) == 0)
				{
					$add = $add . "?module=". $line;
					continue;
				}
					$add = $add . "&action" . ($x>2?($x-1):"") . "=". $line;
				if ($x == COUNT($cont)-1)
					echo "<span class='current'>" . $line . "</span>";
				else
					echo "<a href='" . $add . "'>" . $line . "</a><span>&rsaquo;</span>";
			}
			echo "</div></div><div class='clear'></div>";
		}
		
		public function showPagination( $url = "", $page = 1, $total, $display=5, $show_extra=false)
		{
			$next_flag = 0;
			$f_flag = 0;
			$start = 1;
			$end = $display;
			if( !$total )
				return 0;
			if( $page%$display == 0 ){
				$page--;
				$f_flag++;
			}
					
			$start = max($start, $display*floor($page/$display));
			$end = max($end, $display*floor($page/$display)+$display);
				
			if( ($end - $start) > ($display-1) )
				$start++;
				
			if( $f_flag )
				$page++;
					
			if( $end < $total/$display )
				$next_flag++;
						
			$end = min( $end, $total/$display + ($total%$display > 0) );
					
            echo '<div class="pagination2">';
            echo '	<ul>';
			if( $start > 1)
			{
				$prev = $start - 1;
				$prev = '<a href="' . $url . '&page=' . $prev . '"><span>&#8592;</span></a>';
            	echo '		<li class="prev">' . $prev . '</li>';
			}
			
			for($i=$start; $i<=$end; $i++){
				if($i == $page){
            		echo '		<li class="curent"><a href="#">' . $i . '</a></li>';
				} else {
            		echo '		<li><a href="' . $url . '&page=' . $i . '">' . $i . '</a></li>';
				}
			}
			$i = 25.0;
			while( $i < 100 )
			{
				$x = floor($total/$display + ($total%$display > 0));
				$x = floor($x * $i / 100);
				if( $x > $end )
				{
            		echo '		<li><span>...</span></li>';
            		echo '		<li><a href="' . $url . '&page=' . $x . '">' . $x . '</a></li>';
					break;
				}
				$i += 25;
			}
			if( $next_flag )
			{
				$next = $end+1;
				$next = '<a href="' . $url . '&page=' . $next . '"><span>&#8594;</span></a>';
				echo '		<li class="next">' . $next . '</li>';
			}
            echo '	</ul>';
            echo '</div><!-- .pagination -->';
			if( $show_extra )
			{
    			if ( (($page-1)*$display+1) == $total )
    			{
    				echo '<p class="pagination_info">Displaying ' . (($page-1)*$display+1) . ' (of ' . $total . ' items)</p>';
    			}else if ($page*$display > $total)
    			{
               		echo '<p class="pagination_info">Displaying ' . (($page-1)*$display+1) . ' to ' . $total . ' (of ' . $total . ' items)</p>';
    			}else
               		echo '<p class="pagination_info">Displaying ' . (($page-1)*$display+1) . ' to ' . $page*$display . ' (of ' . $total . ' items)</p>';
			}
		}
        /*
         * Please leave the credit intact
         */
        public static function about()
        {
            echo '<p>All Rights Reserved 2013-2014</p>';
            echo '<p>Developed by Rudolp G. Esquilon</p>';
        }
        function encrept($str)
        {
            $keys = str_split($str);
            $str  = "";
            $key  = rand(1, 5);
            for ($x = 0; $x < count($keys); $x++)
                $str .= chr(ord($keys[$x]) + $key);
            return $key . $str;
        }
        function decrept($str)
        {
            $key  = substr($str, 0, 1);
            $keys = str_split($str);
            $str  = "";
            for ($x = 1; $x < count($keys); $x++)
                $str .= chr(ord($keys[$x]) - $key);
            return $str;
        }
        public function downloadFile($file)
        {
            if (file_exists($file))
            {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename=' . basename($file));
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                ob_clean();
                flush();
                readfile($file);
                exit;
            } //file_exists($file)
        }
		public function logger($module, $msg){
			$login = self::$user;
			if (($id=$login->aid))
			{
    			$sql = "INSERT INTO transaction_log(module, message, datetime, aid) VALUES('%s', '%s', NOW(), %d)";
    			Connection::getConnect();
    			Connection::setQueryf($sql, $module, $msg, $id);
			}
		}
    }
    /*
    Server side checking of client browser.
    */
    function getBrowser()
    {
        $u_agent  = $_SERVER['HTTP_USER_AGENT'];
        $bname    = 'Unknown';
        $platform = 'Unknown';
        $version  = "";
        //First get the platform?
        if (preg_match('/linux/i', $u_agent))
        {
            $platform = 'linux';
        } //preg_match('/linux/i', $u_agent)
        elseif (preg_match('/macintosh|mac os x/i', $u_agent))
        {
            $platform = 'mac';
        } //preg_match('/macintosh|mac os x/i', $u_agent)
        elseif (preg_match('/windows|win32/i', $u_agent))
        {
            $platform = 'windows';
        } //preg_match('/windows|win32/i', $u_agent)
        // Next get the name of the useragent yes seperately and for good reason
        if (preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent))
        {
            $bname = 'Internet Explorer';
            $ub    = "MSIE";
        } //preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent)
        elseif (preg_match('/Firefox/i', $u_agent))
        {
            $bname = 'Mozilla Firefox';
            $ub    = "Firefox";
        } //preg_match('/Firefox/i', $u_agent)
        elseif (preg_match('/Chrome/i', $u_agent))
        {
            $bname = 'Google Chrome';
            $ub    = "Chrome";
        } //preg_match('/Chrome/i', $u_agent)
        elseif (preg_match('/Safari/i', $u_agent))
        {
            $bname = 'Apple Safari';
            $ub    = "Safari";
        } //preg_match('/Safari/i', $u_agent)
        elseif (preg_match('/Opera/i', $u_agent))
        {
            $bname = 'Opera';
            $ub    = "Opera";
        } //preg_match('/Opera/i', $u_agent)
        elseif (preg_match('/Netscape/i', $u_agent))
        {
            $bname = 'Netscape';
            $ub    = "Netscape";
        } //preg_match('/Netscape/i', $u_agent)
        // finally get the correct version number
        $known   = array(
            'Version',
            $ub,
            'other'
        );
        $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
        if (!preg_match_all($pattern, $u_agent, $matches))
        {
            // we have no matching number just continue
        } //!preg_match_all($pattern, $u_agent, $matches)
        // see how many we have
        $i = count($matches['browser']);
        if ($i != 1)
        {
            //we will have two since we are not using 'other' argument yet
            //see if version is before or after the name
            if (strripos($u_agent, "Version") < strripos($u_agent, $ub))
            {
                $version = $matches['version'][0];
            } //strripos($u_agent, "Version") < strripos($u_agent, $ub)
            else
            {
                $version = $matches['version'][1];
            }
        } //$i != 1
        else
        {
            $version = $matches['version'][0];
        }
        // check if we have a number
        if ($version == null || $version == "")
        {
            $version = "?";
        } //$version == null || $version == ""
        return array(
            'userAgent' => $u_agent,
            'name' => $bname,
            'version' => $version,
            'platform' => $platform,
            'pattern' => $pattern
        );
    }
?>